import React from 'react';
import {
  Descriptions,
  Typography,
  Tag,
  List,
  Alert,
  Space,
  Divider,
} from 'antd';
import styles from './TranslationResult.module.css';

const { Text, Link, Title } = Typography;

const TranslationResult = ({ data }) => {
  if (!data || data.errorCode !== '0') {
    return (
      <Alert
        message='翻译错误'
        description={`错误代码：${data?.errorCode}`}
        type='error'
        showIcon
      />
    );
  }

  const partOfSpeechDict = {
    n: '名词',
    v: '动词',
    adj: '形容词',
    adv: '副词',
    prep: '介词',
    pron: '代词',
    conj: '连词',
    det: '冠词',
    interj: '感叹词',
    num: '数词',
  };

  const getPartOfSpeech = exp => {
    const matches = exp.match(/^\w+\./);
    return matches ? matches[0] : '';
  };

  const renderExamTypes = () => {
    if (!data?.basic?.exam_type) return null;
    return data.basic.exam_type.map((type, index) => (
      <Tag
        key={index}
        color={index % 2 === 0 ? 'geekblue' : 'purple'}>
        {type}
      </Tag>
    ));
  };

  const renderBasicExplains = () => {
    if (!data?.basic?.explains) return null;
    return data.basic.explains.map((exp, index) => (
      <Text key={index}>
        {exp}
        {index < data.basic.explains.length - 1 && ', '}
      </Text>
    ));
  };

  const renderPhonetic = () => {
    if (!data?.basic?.phonetic) return null;
    return data.basic.phonetic ? `[${data.basic.phonetic}]` : '';
  };

  const renderPartsOfSpeech = () => {
    if (!data?.basic?.explains) return null;
    const partsOfSpeech = data.basic.explains.map(getPartOfSpeech);
    const uniquePartsOfSpeech = [...new Set(partsOfSpeech)];

    return uniquePartsOfSpeech.map((part, index) => (
      <Tag
        key={index}
        color={index % 2 === 0 ? 'magenta' : 'green'}>
        {partOfSpeechDict[part.slice(0, -1)] || part.slice(0, -1)}
      </Tag>
    ));
  };

  return (
    <div className={styles.container}>
      <Title
        className={styles.title}
        level={4}>
        翻译结果
      </Title>
      <Descriptions
        size='small'
        column={1}
        bordered>
        <Descriptions.Item
          className={styles.item}
          label='源语言'>
          {data.query}
        </Descriptions.Item>
        <Descriptions.Item
          className={styles.item}
          label='音标'>
          {renderPhonetic()}
        </Descriptions.Item>
        <Descriptions.Item
          className={styles.item}
          label='翻译'>
          {renderBasicExplains()}
        </Descriptions.Item>
        <Descriptions.Item
          className={styles.item}
          label='词性'>
          {renderPartsOfSpeech()}
        </Descriptions.Item>
        <Descriptions.Item
          className={styles.item}
          label='考试类型'>
          {renderExamTypes()}
        </Descriptions.Item>
      </Descriptions>
      <Divider />
    </div>
  );
};
export default TranslationResult;
